package com.marvels.product.param.api.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.utils.CacheUtils;
import com.marvels.product.param.api.ProductChannelApi;
import com.marvels.product.param.dto.CascadeChannelDto;
import com.marvels.product.productmanage.dao.McptChannelDao;
import com.marvels.product.productmanage.dto.McptChannelDto;

@Service
public class ProductChannelImpl implements ProductChannelApi {

	@Autowired
	private McptChannelDao mcptChannelDao;

	@Override
	public CascadeChannelDto mcptChannelInfo(McptChannelDto mcptChannelDto) {
		String redisKey=MarvelsConstant.PRODUCT_INFO_LIST_KEY;
		CascadeChannelDto cascadeChannelDto=new CascadeChannelDto();
		Object object=CacheUtils.getCacheObject(redisKey);
		if(object!=null){
			cascadeChannelDto=(CascadeChannelDto)object;
		}else{
			
			List<McptChannelDto> dataList = mcptChannelDao.channelInfo(mcptChannelDto);
			if (dataList != null && dataList.size() > 0) {
				Map<String, Object> map = new HashMap<>();
				for (McptChannelDto mcptChannel : dataList) {
					if (map.get(mcptChannel.getPatternCode()) == null) {
						map.put(mcptChannel.getPatternCode(), mcptChannel.getPatternCode());
					}
				}
				List<Map<String,Object>> returnList=new ArrayList<>();
				for(String key:map.keySet()){
					Map<String, Object> dataMap = new HashMap<>();
					List<McptChannelDto> list=new ArrayList<>();
					for (McptChannelDto mcptChannel : dataList) {
						if(key.equals(mcptChannel.getPatternCode())){
							list.add(mcptChannel);
						}
					}
					dataMap.put("patternList",list);
					dataMap.put("patternCode",key);
					if(list!=null && list.size()>0){
						dataMap.put("patternName",list.get(0).getPatternName());
					}
					returnList.add(dataMap);
				}
				cascadeChannelDto.setPatternList(returnList);
			}
			CacheUtils.cacheObject(redisKey, cascadeChannelDto);
		}
		return cascadeChannelDto;
	}

	@Override
	public List<McptChannelDto> mcptChannelAllInfo(McptChannelDto mcptChannelDto) {
		String redisKey=MarvelsConstant.CAHNNEL_ALL_INFO_LIST_KEY;
		List<McptChannelDto> dto=null;
		Object object=CacheUtils.getCacheObject(redisKey);
		if(object!=null){
			dto = (List<McptChannelDto>)object;
		}
		if(CollectionUtils.isEmpty(dto)){
			List<McptChannelDto> dataList = mcptChannelDao.channelInfo(mcptChannelDto);
			CacheUtils.cacheObject(redisKey, dataList);
		}
		return dto;
	}

}
